import 'dart:developer';
import 'dart:io';

import 'package:edu/constants/app_strings.dart';
import 'package:edu/utils/data_fetcher.dart';
import 'package:flutter/material.dart';
import 'package:edu/utils/account_info.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:image_picker/image_picker.dart';
import 'package:image/image.dart' as img;

class AccountProfileSettingPageLogic extends ChangeNotifier {
  // 用户信息
  String? get nickname => AccountInfo.shared.userProfile?.name;
  String? get profession => AccountInfo.shared.userProfile?.profession;
  String? get location => AccountInfo.shared.userProfile?.region;
  String? get gender => AccountInfo.shared.userProfile?.gender;
  String? get introduction => AccountInfo.shared.userProfile?.introduction;

  // 加载中
  bool isLoading = false;
  // 错误
  bool isError = false;
  // 数据为空
  bool get isProfileEmpty => AccountInfo.shared.userProfile == null;

  void _userProfileListener() {
    notifyListeners();
  }

  void init() {
    AccountInfo.shared.userProfileNotifier.addListener(_userProfileListener);

    // 延迟加载数据
    Future.delayed(Duration.zero, () {
      loadUserProfile();
    });
  }

  @override
  void dispose() {
    AccountInfo.shared.userProfileNotifier.removeListener(_userProfileListener);
    super.dispose();
  }

  // 加载用户信息
  Future<void> loadUserProfile() async {
    if (AccountInfo.shared.userProfile != null || isLoading) {
      return;
    }

    try {
      EasyLoading.show(
        indicator: const CircularProgressIndicator(),
        maskType: EasyLoadingMaskType.clear,
        dismissOnTap: false,
      );

      isLoading = true;
      isError = false;
      notifyListeners();

      // 获取用户信息
      final response = await DataFetcher.shared.userApi.getUserProfile();
      isLoading = false;
      EasyLoading.dismiss(); // 隐藏加载框

      if (response.code == 0 && response.profile != null) {
        // 更新用户信息
        AccountInfo.shared.updateUserProfile(response.profile!);
      } else {
        isError = true;
        EasyLoading.showError(response.message ?? AppStrings.unknownError);
      }
      notifyListeners();
    } catch (e) {
      isLoading = false;
      isError = true;
      notifyListeners();
      EasyLoading.dismiss();
      EasyLoading.showError(e.toString());
    }
  }

  // 修改用户头像
  Future<void> updateUserAvatar() async {
    try {
      final picker = ImagePicker();
      final phone = await picker.pickImage(source: ImageSource.gallery);
      if (phone != null) {
        EasyLoading.show(
          status: AppStrings.loadingPhoto,
          indicator: const CircularProgressIndicator(),
          maskType: EasyLoadingMaskType.black,
          dismissOnTap: true,
        );
        // 获取图片文件
        final file = File(phone.path);
        final bytes = await file.readAsBytes();
        final image = img.decodeImage(bytes);

        if (image == null) {
          EasyLoading.dismiss();
          EasyLoading.showError(AppStrings.invalidImage);
          return;
        }

        // 图片处理,限制图片大小
        final img.Image resized;
        if (image.width > image.height) {
          if (image.width > 600) {
            resized = img.copyResize(image, width: 600);
          } else {
            resized = image;
          }
        } else {
          if (image.height > 600) {
            resized = img.copyResize(image, width: 600);
          } else {
            resized = image;
          }
        }

        final jpg = img.encodeJpg(resized);
        EasyLoading.dismiss();

        EasyLoading.show(
          status: AppStrings.uploadingPhoto,
          indicator: const CircularProgressIndicator(),
          maskType: EasyLoadingMaskType.black,
          dismissOnTap: false,
        );

        final response = await DataFetcher.shared.userApi.updateUserAvatar(jpg);
        EasyLoading.dismiss();
        if (response.code == 0 && response.result?.field == 'avatar') {
          EasyLoading.showSuccess(AppStrings.updateSuccess);
          AccountInfo.shared.updateAvatar(response.result?.value);
          // 刷新用户信息
          loadUserProfile();
        } else {
          EasyLoading.showError(response.message ?? AppStrings.unknownError);
        }
      }
    } on PlatformException catch (e) {
      EasyLoading.dismiss();
      if (e.code == 'photo_access_denied') {
        EasyLoading.showError(AppStrings.photoAccessDenied);
      }
      log('PlatformException: ${e.toString()}');
    } catch (e) {
      EasyLoading.dismiss();
      log('Error: ${e.toString()}');
    }
  }

  // 修改用户性别
  void updateGender(String gender) async {
    if (gender == this.gender) {
      return;
    }

    try {
      EasyLoading.show(
        indicator: const CircularProgressIndicator(),
        maskType: EasyLoadingMaskType.black,
        dismissOnTap: false,
      );
      final response = await DataFetcher.shared.userApi.updateUserGender(
        gender,
      );
      EasyLoading.dismiss();
      if (response.code == 0 && response.result?.field == 'gender') {
        EasyLoading.showSuccess(AppStrings.updateSuccess);
        AccountInfo.shared.updateGender(response.result?.value);
      } else {
        EasyLoading.showError(response.message ?? AppStrings.unknownError);
      }
    } catch (e) {
      EasyLoading.dismiss();
      EasyLoading.showError(e.toString());
      log('Error: $e');
    }
  }
}
